# coding=utf-8

import paramiko
import psutil
import time

# 定义连接参数
hostname = '192.168.79.200'
username = 'Administrator'
password = 'Ugreen.68'
port = 22  # SSH端口

# 定义要检查的进程名
process_name = 'cmd.exe'

# 定义日志文件路径
log_file_path = 'D:\\TZC\\nas_auto_test\\logs\\nas_auto_test.log'

# 定义要搜索的关键字
keywords = ['error', '失败']

def check_process():
    """检查特定进程是否正在运行"""
    for proc in psutil.process_iter(['pid', 'name']):
        if process_name.lower() in proc.info['name'].lower():
            return True
    return False

def read_and_search_log(file_path, keywords):
    """读取日志文件并搜索关键字"""
    with open(file_path, 'r') as file:
        lines = file.readlines()
        for line in lines:
            for keyword in keywords:
                if keyword.lower() in line.lower():
                    print(f"找到关键字 '{keyword}' 在行: {line.strip()}")

def main():
    while True:
        try:
            # 连接到远程服务器
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(hostname, port=port, username=username, password=password)

            # 检查进程是否正在运行
            if check_process():
                # 读取并搜索日志文件
                read_and_search_log(log_file_path, keywords)

        except Exception as e:
            print(f"发生错误: {e}")

        # 每隔一段时间执行一次（例如，每5分钟）
        time.sleep(300)

if __name__ == "__main__":
    main()